// 文件夹管理
import React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { Button, Form, Input, message, Modal, Space, Table, Row, Col, Tooltip, Popconfirm } from 'antd';
import AnalyseCategorySelect from 'src/pages/AnalyseManage/Components/AnalyseCategorySelect';

import {
	DeleteOutlined,
	PlusCircleOutlined,
	SnippetsOutlined,
	SearchOutlined,
} from '@ant-design/icons';
import {
	createAnalyseCategory,
	delAnalyseCategory,
	getCategoryTree,
	updateAnalyseCategory,
	initTenantAnalyse,
	batchDelAnalyseCategories, delAnalysePage, updateAnalysePage
} from 'src/services/AnalyseManage';
import FormItem from 'antd/lib/form/FormItem';
import { FormInstance } from 'antd/lib/form';
import AuthAssignment from './components/AuthAssignment';
import styles from './index.module.scss';
import BdhButton from 'src/pages/Components/BdhButton';

interface listItemType {
	name: string;
	id: string;
	effect: string;
}

interface IProps {
	record: listItemType;
	handleEdit: ( item: listItemType, isEdit: boolean ) => void;
	handleDelete: ( item: listItemType ) => void;
	btnAuth: any;
}

//	操作栏组件
const OperateComponent = React.memo( ( props: IProps ) => {
	return props.btnAuth.includes( 'bi_folderManage_action' ) ? (
		<Space size="middle">
			<Tooltip placement="topRight" title="分配权限">
				<Button
					type="text" icon={ <span className={ `iconfont bdhquanxian ${ styles.green_btn }` }></span> }
					onClick={ () => {
					} }></Button>
			</Tooltip>
			<Tooltip placement="topRight" title="重命名">
				<Button
					type="text" icon={ <span className={ `iconfont bdhxiugai ${ styles.green_btn }` }></span> }
					onClick={ () => props.handleEdit( props.record, true ) }></Button>
			</Tooltip>

			<Tooltip placement="topRight" title="删除">
				<Popconfirm
					okText="确定" cancelText="取消" title="确定删除这一项？" placement="bottom"
					onConfirm={ () => props.handleDelete( props.record ) }>
					<Button type="text" icon={ <span className={ `iconfont bdhshanchu ${ styles.green_btn }` }></span> }></Button>
				</Popconfirm>
			</Tooltip>
		</Space>
	) : (
		<Space size="middle"></Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

class FolderManage extends React.Component<RouteComponentProps & { btnAuth:any }> {
	formRef = React.createRef<FormInstance>();
	state: any = {
		data: [],
		modalVisible: false,
		currentData: {},
		defaultSelectedKeys: [],
		isAuthAssign: false,
		isEdit: false,
		selectedRowKeys: [],
		keyword: '',
		timer: null,
		tableLoading: false,
		pageSize: 10,
		total: 0
	};

	//	列表表头配置
	columns = [
		{
			title: '文件夹名称',
			dataIndex: 'name'
		},
		{
			title: '描述',
			dataIndex: 'des'
		},
		{
			title: '操作',
			key: 'action',
			// eslint-disable-next-line react/display-name
			render: ( record: listItemType ) => (
				<OperateComponent
					record={ record }
					handleEdit={ this.onEdit }
					handleDelete={ this.onDel }
					btnAuth={ this.props.btnAuth }
				></OperateComponent>
			)

		},
	];

	handleSelectionChange = ( selectedRowKeys ) => {
		this.setState( { selectedRowKeys } );
	};

	componentDidMount() {
		this.loadDatas();
	}

	loadDatas = async () => {
		let response = await getCategoryTree( {
			name: this.state.keyword
		} );
		if ( response.data && response.data.success ) {
			this.setState( { data: response.data.data } );
		}
	};
	okHandle = async () => {
		this.formRef.current
			.validateFields()
			.then( async ( values: any ) => {
				console.log( values );
				let response;
				if ( !this.state.currentData.id ) {
					let data = { ...values };
					response = await createAnalyseCategory( data );
				} else {
					let currentData = this.state.currentData;
					let data = {
						id: currentData.id,
						name: values.name,
						des: values.des,
					};
					if( this.state.currentData.childrenType === 'PAGE' ) {
						response = await updateAnalysePage( data );
					} else {
						response = await updateAnalyseCategory( data );
					}


				}
				if ( response.data && response.data.success ) {
					this.setState( { modalVisible: false } );
					this.loadDatas();
				}
			} )
			.catch( ( errorInfo ) => {
				// error
				// console.log( errorInfo );
				// form.resetFields();
			} );
	};
	onCancel = () => {
		this.setState( { modalVisible: false } );
	};
	onNew = () => {
		this.setState( { modalVisible: true, currentData: {} } );
	};
	onEdit = ( record ) => {
		this.setState( { modalVisible: true, currentData: record } );
		this.setTreeDefaultKeys();
	};

	setTreeDefaultKeys = () => {
		let defaultSelectedKeys: any[] = [];
		if ( this.state.currentData && this.state.currentData.parentId ) {
			defaultSelectedKeys.push( this.state.currentData.parentId );
		}
		this.setState( {
			defaultSelectedKeys: defaultSelectedKeys,
		} );
	};
	onAuthAssign = () => {
		this.setState( {
			isAuthAssign: true,
		} );
	};

	onDel = async ( record ) => {
		console.log( record );
		let response;
		if( record.childrenType === 'PAGE' ) {
			response = await delAnalysePage( record.id );
		} else {
			response = await delAnalyseCategory( record.id );
		}

		if ( response.data && response.data.success ) {
			this.loadDatas();
			message.success( '操作成功' );
		}
	};
	/**
	 *
	 *
	 */
	initTenantAnalyse = async () => {
		let response = await initTenantAnalyse( {} );
		if ( response.data && response.data.success ) {
			message.success( '初始化成功' );
		}
	};

	onBatchDel = async () => {
		let response = await batchDelAnalyseCategories( {
			ids: this.state.selectedRowKeys,
		} );
		if ( response.data && response.data.success ) {
			message.success( '批量删除成功' );
			this.loadDatas();
			this.setState( { selectedRowKeys: [] } );
		}
	};

	//	输入框搜索
	handleSearchInput = ( e ) => {
		e.persist();

		let value = e.target.value;
		this.setState( {
			keyword: value
		} );

		if ( this.state.timer ) clearTimeout( this.state.timer );
		let timer = setTimeout( () => {
			this.loadDatas();
		}, 300 );
		this.setState( {
			timer: timer
		} );

	};

	selectFolder = ( node: any ) => {
		this.formRef.current.setFieldsValue( { parentId: node.id } );
		const currentData = { ...this.state.currentData, parentId: node.id };
		this.setState( {
			currentData: currentData,
		} );
	};

	//	切换页码
	handlePageChange = ( pageNumber: number ) => {
		this.setState(
			{
				page: pageNumber,
			},
			() => {
				this.loadDatas();
			}
		);
	};

	//	修改每页数量
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size
		} );
	};

	render() {
		const btnAuth = this.props.btnAuth;
		return (
			<div className={ styles.folder_container }>
				<div className={ styles.folder_top }>
					<Row justify="space-between">
						<Col span={ 20 } style={ { textAlign: 'left' } }>
							{
								btnAuth.includes( 'bi_folderManage_batchDel' ) && (
									<Popconfirm
										okText="确定" cancelText="取消" title="确定删除选中数据？" placement="bottom"
										onConfirm={ this.onBatchDel }>
										<BdhButton
											align='horizontal'
											label='批量删除' className="grey-transpanent"
											onClick={ null }
											icon={ <DeleteOutlined/> }></BdhButton>
									</Popconfirm>
								)
							}
							{
								btnAuth.includes( 'bi_folderManage_add' ) && (
									<BdhButton
										align='horizontal'
										label='新建' className="primary-transpanent"
										onClick={ this.onNew }
										icon={ <PlusCircleOutlined/> }></BdhButton>
								)
							}
							{
								btnAuth.includes( 'bi_folderManage_init' ) && (
									<BdhButton
										align='horizontal'
										label='初始化默认文件夹' className="primary-transpanent"
										onClick={ this.initTenantAnalyse }
										icon={ <SnippetsOutlined/> }></BdhButton>
								)
							}
						</Col>
						<Col span={ 4 }>
							<Input
								placeholder="请输入"
								allowClear
								onChange={ this.handleSearchInput }
								prefix={ <SearchOutlined/> }
							/>
						</Col>
					</Row>
				</div>
				<div className={ styles.folder_table }>

					<Table
						loading={ this.state.tableLoading }
						rowSelection={ { type: 'checkbox', checkStrictly: false, onChange: this.handleSelectionChange } }
						scroll={ { x: '100%' } }
						tableLayout='fixed'
						columns={ this.columns }
						dataSource={ this.state.data }
						bordered={ true }
						rowKey={ ( row: listItemType ) => row.id }
						size='middle'
						pagination={ {
							showSizeChanger: true,
							pageSize: this.state.pageSize,
							total: this.state.total,
							onChange: this.handlePageChange,
							onShowSizeChange: ( current, size ) => this.setPageSize( size ),
							showTotal: total => `共 ${ total } 条`,
						} }
					/>
				</div>

				<Modal
					destroyOnClose
					title="添加文件夹"
					visible={ this.state.modalVisible }
					onCancel={ this.onCancel }
					onOk={ this.okHandle }
					width={ '60%' }
					okText='确定'
					cancelText='取消'
				>
					<Form
						layout="horizontal"
						ref={ this.formRef }
						initialValues={ this.state.currentData }
					>
						<FormItem
							labelCol={ { span: 5 } }
							wrapperCol={ { span: 15 } }
							label="名称"
							name="name"
						>
							<Input placeholder="名称不能为空"/>
						</FormItem>
						<FormItem
							labelCol={ { span: 5 } }
							wrapperCol={ { span: 15 } }
							label="描述"
							name="des"
						>
							<Input placeholder="描述不能为空"/>
						</FormItem>
						{/*编辑时隐藏文件夹结构*/ }
						{
							!this.state.currentData.id && (
								<FormItem
									labelCol={ { span: 5 } }
									wrapperCol={ { span: 15 } }
									label="请选择文件夹"
									name="parentId"
									rules={ [ { required: true, message: '不能为空！' } ] }
								>
									<AnalyseCategorySelect
										onSelect={ ( node ) => {
											this.selectFolder( node );
										} }
										defaultSelectedKeys={ this.state.defaultSelectedKeys }
									></AnalyseCategorySelect>
								</FormItem>
							)
						}

						{/*选择图表先去掉*/ }
						{/*<FormItem*/ }
						{/*	labelCol={ { span: 5 } }*/ }
						{/*	wrapperCol={ { span: 15 } }*/ }
						{/*	label="选择图标"*/ }
						{/*	rules={ [ { required: true, message: '不能为空！' } ] }*/ }
						{/*></FormItem>*/ }
					</Form>
				</Modal>

				{ this.state.isAuthAssign && (
					<AuthAssignment
						visible={ this.state.isAuthAssign }
						cancelHandle={ () => {
							this.setState( {
								isAuthAssign: false,
							} );
						} }
						okHandle={ () => {
							this.setState( {
								isAuthAssign: false,
							} );
						} }
					></AuthAssignment>
				) }
			</div>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		btnAuth: state.btnAuth,
	};
};

export default connect( mapStateToProps )( FolderManage );
